package edu.visualizetion.info.sensorcollection;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import java.util.Map;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServiceImpl extends UnicastRemoteObject implements IService {
	
	private static final long serialVersionUID = -307373949982876625L;

	private static final Logger LOGGER = LoggerFactory.getLogger(ServiceImpl.class);
	private InetAddress inetAddress = null;
	private String hostAddress = null;
	private static long G = 1024*1024*1024;

	public ServiceImpl() throws RemoteException {
		super();
		
		try {
			inetAddress = InetAddress.getLocalHost();
			hostAddress = inetAddress.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			LOGGER.error("initialize the address failed");
			throw new RuntimeException("initialize the address failed");
		}
		SigarFactory.InitSigar();
	}

	@Override
	public Record getStatus() throws RemoteException, SigarException {

		// set name and time
		Record record = new Record();
		record.setNameOfServer(hostAddress);
		record.setTime(System.currentTimeMillis());
		// get cpu information
		try {
			CpuPerc cpuPerc = SigarFactory.getCpu();
			record.setCpuRatio(cpuPerc.getCombined());
		} catch (SigarException e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
			throw e;
		}
		// get memory information
		Mem mem = SigarFactory.getMemory();
		record.setMemTotal(mem.getTotal()/G);
		record.setMemUsed(mem.getUsed()/G);
		record.setMemFree(mem.getFree()/G);
		record.setMemFreeRatio(mem.getFreePercent());
		record.setMemUsedRatio(mem.getUsedPercent());
		// get disk information
		List<Object> diskInfo = SigarFactory.getDisk();
		record.setDiskReadMap((Map<String, Long>) diskInfo.get(0));
		record.setDiskWriteMap((Map<String, Long>) diskInfo.get(1));
		// get net information
		Pair<Long, Long> net = SigarFactory.getNetRecvSend(hostAddress);
		if (net == null) {

		} else {
			record.setNetRecv(net.getLeft());
			record.setNetSend(net.getRight());
		}

		return record;
	}

	@Override
	public String getServiceName() throws RemoteException {

		return hostAddress;
	}
}
